import Mn from 'backbone.marionette';

import TextAreaWidget from '../../widgets/TextAreaWidget.js';
import ModalFormBehavior from '../../base/behaviors/ModalFormBehavior.js';
import SelectWidget from "../../widgets/SelectWidget";
import Radio from "backbone.radio";
import CheckboxWidget from "../../widgets/CheckboxWidget";
import {
    SafeString
} from '../../string.js';
import {
    hideRegion,
    showRegion
} from '../../backbone-tools.js';
import CheckboxListWidget from '../../widgets/CheckboxListWidget.js';
const template = require('./templates/StatusLogEntryFormPopupView.mustache');

/** Popup to add freetext memo
 *
 * A single `description` field is split/unsplit from/to two fields on the model:
 * - label (first line)
 * - description (the remainder, if any).
 *
 * See splitDescriptionfield()/mergeDescriptionField()
 *
 * Requirements:
 * - a config channel answering to ('get:options', 'visibilities')
 */
const StatusLogEntryFormPopupView = Mn.View.extend({
    // Send the whole model on submit
    partial: false,
    behaviors: [ModalFormBehavior],
    template: template,
    regions: {
        'description': '.field_description',
        'visibility': '.field_visibility',
        'pinned': '.field_pinned',
        "notify": ".field_notify",
        "notification_recipients": ".field_notification_recipients",
    },
    ui: {
        form: 'form',
        submit: 'button[type=submit]',
    },
    // Listen to the current's view events
    events: {
        'click @ui.submit': 'onSubmit'
    },
    childViewEvents: {
        'finish:pinned': 'onChangePinned',
        'finish:visibility': 'onChangeVisibility',
        'finish:notify': 'onChangeNotify',
    },

    onChangePinned(pinnedValue) {
        const pinnedCount = this.options.destCollection.getPinnedCount();
        if ((pinnedValue === true) && (pinnedCount >= 3)) {
            alert(
                `Il y déjà ${pinnedCount} mémos épinglés. ` +
                "Tous ne pourront pas être affichés à la fois."
            );
        }
    },
    onChangeVisibility(visibility) {
        if (visibility != 'public') {
            this.hideNotifyField();
            this.hideNotifyRecipientsField();
        } else {
            this.showNotifyField();
            this.showNotifyRecipientsField();
        }
    },
    onChangeNotify(notifyValue) {
        if (notifyValue) {
            this.showNotifyRecipientsField();
        } else {
            this.hideNotifyRecipientsField();
        }
    },
    initialize(options) {
        this.model = options.model;
        this.config = Radio.channel('config');
        this.notification_recipients = this.config.request(
            'get:options', 'notification_recipients'
        );
    },
    onRender() {
        this.showTextField();
        this.showVisibilityField();
        this.showPinnedField();
        this.showNotifyField();
        this.showNotifyRecipientsField();

    },
    showTextField() {
        const view = new TextAreaWidget({
            label: "Texte",
            description: "La première ligne sera considérée comme le titre du mémo",
            field_name: 'description',
            value: this.mergeDescriptionField(
                this.model.get('label'),
                this.model.get('comment'),
            ),
            required: true,
            rows: 4,
        });
        this.showChildView('description', view);
    },
    showVisibilityField() {
        const docLink = "https://doc.endi.coop/co/MemoNotification.html?ts=l1yxri90#xtlcQNlyvEfgC5vqW3jVOf";
        const docTitle = "Ouvrir la documentation dans une nouvelle fenêtre";
        const view = new SelectWidget({
            options: this.config.request('get:options', 'visibilities'),
            title: "Visibilité",
            field_name: "visibility",
            value: this.model.get('visibility'),
            description: new SafeString(
                `Les mémos « Perso » sont <a target=_blank href="${docLink}" title="${docTitle}" aria-label="${docTitle}">visibles par les administrateurs de l'application</a> mais pas par le reste de l'équipe d'appui.`
            ),
        });
        this.showChildView('visibility', view);
    },
    showPinnedField() {
        const view = new CheckboxWidget({
            inline_label: "Épinglé",
            description: "Ce mémo sera épinglé en début de liste",
            true_val: true,
            false_val: false,
            field_name: "pinned",
            value: this.model.get('pinned'),
        });
        this.showChildView('pinned', view);
    },
    showNotifyField() {
        if (!this.notification_recipients || this.notification_recipients.length == 0) {
            return
        };
        const view = new CheckboxWidget({
            inline_label: "Envoyer une notification",
            true_val: true,
            false_val: false,
            field_name: "notify",
            value: this.model.get('notify'),
            description: " NB : Les notifications ne peuvent être envoyées que pour les mémos Public"
        })
        this.showChildView('notify', view);
        const region = this.getRegion('notify');
        showRegion(region);
    },
    hideNotifyField() {
        const region = this.getRegion('notify');
        hideRegion(region);
    },
    showNotifyRecipientsField() {
        if (!this.notification_recipients || this.notification_recipients.length == 0) {
            return
        };
        const view = new CheckboxListWidget({
            options: this.notification_recipients,
            title: "Destinataire(s)",
            value: this.model.get('notification_recipients'),
            field_name: "notification_recipients",
            id_key: "id",
            layout: "two_cols",
        })
        this.showChildView('notification_recipients', view);
        const region = this.getRegion('notification_recipients');
        showRegion(region);
    },
    hideNotifyRecipientsField() {
        const region = this.getRegion('notification_recipients');
        hideRegion(region);
    },
    afterSerializeForm(datas) {
        _.extend(datas, this.splitDescriptionField(datas.description));
        delete datas['description']
        return datas;
    },
    splitDescriptionField(text) {
        const separator_position = text.search('\n');
        if (separator_position >= 0) {
            return {
                label: text.substring(0, separator_position).trim(),
                comment: text.substring(separator_position).trim(),
            };
        } else {
            return {
                label: text.trim(),
                comment: ''
            };
        }
    },
    mergeDescriptionField(label, comment) {
        return `${label}\n\n${comment}`.trim();
    },
    templateContext() {
        const edit = this.getOption('edit');
        return {
            title: edit ? "Modifier ce mémo" : "Ajouter un mémo"
        };
    },
});
export default StatusLogEntryFormPopupView;
